import Request from '@/js_sdk/luch-request/luch-request/index.js'
export const http = new Request()

http.setConfig((config) => {
	/* config 为默认全局配置*/
	config.baseURL = 'https://wyxny.19w.top/' /* 根域名 */
	return config
})

//请求前拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	if (config.method == 'GET') {
		config.header = {
			'content-type': 'application/x-www-form-urlencoded'
		}
	} else {
		config.header = {
			'content-type': 'application/json'
		}
	}

	let uid;
	//获取存储的token
	// #ifdef MP-WEIXIN
	uid = uni.getStorageSync('userinfo').user_id || ''
	// #endif
	// #ifdef H5
	let user_id = ''
	if (uni.getStorageSync('userinfo')) {
		user_id = JSON.parse(uni.getStorageSync('userinfo')).user_id
	}
	uid = user_id
	// #endif
	//获取存储的token
	config.header.uid = uid;
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})

// 请求后拦截器
http.interceptors.response.use(async (response) => {
	var responseTO = response.data
	if (responseTO.msg == "用户不存在") {
		uni.reLaunch({
			url: "/pagesHome/logo/logo"
		})
		return Promise.reject(responseTO.msg)
	}
	if (responseTO.code !== 200) {
		uni.showToast({
			title: responseTO.msg,
			icon: 'none',
			mask: true
		})
		return Promise.reject(responseTO.msg)
	}
	if (responseTO.msg == "access_token不能为空" || responseTO.msg == "Expired token" || responseTO
		.msg == 'Wrong number of segments') {
		uni.reLaunch({
			url: "/pagesHome/logo/logo"
		})
		return Promise.reject(responseTO.msg)

		/* 无痛刷新
		if (store.state.user.token.refresh_token) {
			responseTO = await tokenS(response)
		} else {
			uni.reLaunch({
				url: "/pagesHome/login/login"
			})
			return Promise.reject(responseTO.message)
		} */
	}
	return responseTO
}, (response) => {
	// 未登录时清空缓存跳转
	if (response.statusCode == 401) {
		uni.clearStorageSync();
		uni.reLaunch({
			url: "/pages/logo/logo"
		})
	}
	return Promise.reject(response)
})